<template>
  <div class="client-step-container">
    <div class="client-bill-header">
      <div class="client-bill-title">售后单进度</div>
      <div v-if="!showPause && allShow" class="client-bill-continue"
           @click="handleContinue">继&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;续</div>
      <div class="client-bill-pause-and-mend">
        <div v-if="showPause && allShow" class="client-bill-pause" @click="handlePause">暂&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;停</div>
        <div class="client-bill-mend" @click="handleMendInformation">添加维修信息</div>
      </div>
    </div>
    <a-steps>
      <a-step status="finish" v-for="item in processData" :key="item.time" class="single-step">
        <span slot="title" class="process-title">{{item.title}}</span>
        <a-icon slot="icon" :type="item.icon" />
        <div slot="description" class="finish-desc">{{item.desc}}</div>
        <div slot="description" class="finish-time">{{item.time}}</div>
        <div slot="description" class="finish-time">
          <div>{{item.traceDesc}}</div>
          <div class="service-score">{{item.traceSpeed}}</div>
        </div>
        <div slot="description" class="finish-time">
          <div>{{item.evaluateServiceDesc}}</div>
          <div class="detailed-evaluate-content">{{item.evaluateServiceContent}}</div>
        </div>
        <div slot="description" class="finish-time">
          <div>{{item.serviceDesc}}</div>
          <div class="service-score">{{item.serviceAttitude}}</div>
        </div>
        <div slot="description" class="finish-time">
          <div>{{item.evaluateProductDesc}}</div>
          <div class="detailed-evaluate-content">{{item.evaluateProductContent}}</div>
        </div>
      </a-step>
    </a-steps>
    <collection-create-form
      ref="collectionForm"
      :visible="visible"
      @cancel="handleCancel"
      @create="handleCreate"
    />
    <a-modal title="添加维修信息" okText="确定" cancelText="取消" :visible="mendVisible"
             @ok="handleMendCreate" @cancel="handleMendCancel">
      <a-form layout='vertical' :form="mendForm">
        <a-form-item label='请输入维修信息'>
          <a-input
            type='textarea' style="resize: none"
            v-decorator="['record',
              {
                rules: [{ required: true, pattern: /\S/, message: '请输入维修信息!' }],
              }
            ]"
          />
        </a-form-item>

        <a-form-item label='请添加维修图片'>
          <div class="mend-img-container">
            <upload-image @changeFileList="changeFileList"></upload-image>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
  //获取当前时间, 1精确到天, 2精确到分
  function getCurrentDate(format) {
    let now = new Date();
    let year = now.getFullYear(); //得到年份
    let month = now.getMonth();//得到月份
    let date = now.getDate();//得到日期
    let hour = now.getHours();//得到小时
    let minu = now.getMinutes();//得到分钟
    let sec = now.getSeconds();//得到秒
    month = month + 1;
    if (month < 10) month = "0" + month;
    if (date < 10) date = "0" + date;
    if (hour < 10) hour = "0" + hour;
    if (minu < 10) minu = "0" + minu;
    if (sec < 10) sec = "0" + sec;
    let time = "";
    //精确到天
    if (format === 1) {
      time = year + "-" + month + "-" + date;
    }
    //精确到分
    else if (format === 2) {
      time = year + "-" + month + "-" + date + " " + hour + ":" + minu + ":" + sec;
    }
    return time;
  }
  import UploadImage from './Image';
  import api from '@/server/userConfig';
  import axios from 'axios';
  import GLOBAL from "@/api/global_variable"
  const CollectionCreateForm = {
    props: ['visible'],
    beforeCreate () {
      this.form = this.$form.createForm(this, { name: 'form_in_modal' });
    },
    template: `
    <a-modal
      :visible="visible" title='添加暂停原因' okText='确定' cancelText='取消'
      @cancel="() => { $emit('cancel') }"
      @ok="() => { $emit('create') }"
    >
      <a-form layout='vertical' :form="form">
        <a-form-item label='暂停原因'>
          <a-input
            type='textarea' style="resize: none"
            v-decorator="['reason',
              {
                rules: [{ required: true, pattern: /\\S/, message: '请输入暂停原因!' }],
              }
            ]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  `,
  };
  export default {
    name: "SaleProcess",
    components: { CollectionCreateForm, UploadImage },
    props: {
      impedimentState: Number,
      userName: String
    },
    data () {
      return {
        processData: {},
        serviceVal: 0,
        produceVal: 0,
        afterSaleNumber: '',
        repairOrderNumber: '',
        evaluateServiceContent: '',
        evaluateProductContent: '',
        suit: "false",
        showPause: false,
        allShow: false,
        visible: false,
        mendVisible: false,
        picturesId: '',
        evaluateData: {},
        mendForm: this.$form.createForm(this, { name: 'mend_form' }),
      }
    },
    watch: {
      impedimentState: function (newVal) {
        if (newVal !== 0) {
          //console.log(newVal);
          this.showBillContinue(this.suit, newVal);
        }
      },
      serviceVal: function (newVal) {
        if (newVal !== 0) {
          this.getSaleProcess(this.afterSaleNumber);
        }
      }
    },
    mounted () {
      // 获取链接参数username值，然后存进内存中
      const orderNumber = this.$route.query.orderNumber;
      const afterSaleNumber = this.$route.query.saleNumber;
      const suit = this.$route.query.suit;
      this.suit = suit;
      this.afterSaleNumber = afterSaleNumber;
      this.repairOrderNumber = orderNumber;
      this.getBillEvaluateContent(orderNumber);
      this.getSaleProcess(this.afterSaleNumber);
    },
    methods: {
      // 根据单号获取评价内容;
      async getBillEvaluateContent (orderNumber) {
        try {
          const res = await api.reqEvaluateContent({repairOrderNumber: orderNumber});
          if (res.MsgCode !== 0) {
            return
          }
          if (res.Data.serviceScore === 1) {
            this.serviceVal = "★ ☆ ☆ ☆ ";
          } else if (res.Data.serviceScore === 2) {
            this.serviceVal = "★ ★ ☆ ☆ ";
          } else if (res.Data.serviceScore === 3) {
            this.serviceVal = "★ ★ ★ ☆ ";
          } else if (res.Data.serviceScore === 4) {
            this.serviceVal = "★ ★ ★ ★ ";
          }
          //服务态度
          if (res.Data.produceScore === 1) {
            this.produceVal = "★ ☆ ☆ ☆ ";
          } else if (res.Data.produceScore === 2) {
            this.produceVal = "★ ★ ☆ ☆ ";
          } else if (res.Data.produceScore === 3) {
            this.produceVal = "★ ★ ★ ☆ ";
          } else if (res.Data.produceScore === 4) {
            this.produceVal = "★ ★ ★ ★ ";
          }
          this.evaluateServiceContent = res.Data.serviceEvaluate;
          this.evaluateProductContent = res.Data.produceEvaluate;
          this.evaluateData = res.Data;
        } catch (e) {
          if (e) {
            this.getSaleProcess(this.afterSaleNumber);
          }
        }
      },
      // 根据订单编号获取订单流水;
      async getSaleProcess (afterSaleNumber) {
        const res = await api.reqSaleProcess({afterSaleNumber: afterSaleNumber});
        //console.log(res);
        if (res.MsgCode !== 0) {
          return
        }
        for (let i = 0; i < res.Data.length; i++) {
          if (res.Data[i].currentState === 1) {
            res.Data[i].appointorName = "";
            res.Data[i].title = "已报单";
            res.Data[i].icon = "user";
            res.Data[i].desc = "报修订单提交成功："+ res.Data[i].repairListName + "("+ res.Data[i].repairListUsername + res.Data[i].secondDepartment +")";
          } else if (res.Data[i].currentState === 2) {
            res.Data[i].appointorName = res.Data[i].appointor;
            res.Data[i].title = "已指派";
            res.Data[i].icon = "right-square";
            res.Data[i].desc = "已指派工程师：" + res.Data[i].username + "(" + res.Data[i].name + res.Data[i].secondDepartment + ")";
          } else if (res.Data[i].currentState === 3) {
            res.Data[i].appointorName = res.Data[i].operator;
            res.Data[i].title = "已转单";
            res.Data[i].icon = "export";
            res.Data[i].desc = "已转单工程师："+ res.Data[i].name + "(" + res.Data[i].username + res.Data[i].secondDepartment + ")";
          }  else if (res.Data[i].currentState === 4 || res.Data[i].currentState === 6) {
            res.Data[i].title = "已关闭";
            res.Data[i].icon = "close-square";
            res.Data[i].desc = res.Data[i].evaluatorName +"(" + res.Data[i].evaluator + res.Data[i].secondDepartment + ")已评价！";
            res.Data[i].traceSpeed = this.serviceVal;
            res.Data[i].traceDesc = "服务满意度:";
            res.Data[i].serviceAttitude = this.produceVal;
            res.Data[i].serviceDesc = "产品满意度:";
            res.Data[i].evaluateServiceContent = this.evaluateServiceContent;
            res.Data[i].evaluateServiceDesc = "服务回访备注:";
            res.Data[i].evaluateProductContent = this.evaluateProductContent;
            res.Data[i].evaluateProductDesc = "产品回访备注:";
          } else if (res.Data[i].currentState === 5) {
            res.Data[i].title = "待回访";
            res.Data[i].icon = "phone";
            res.Data[i].desc = "待回访";
            res.Data[i].traceSpeed = "";
            res.Data[i].traceDesc = "";
            res.Data[i].serviceAttitude = "";
            res.Data[i].serviceDesc = "";
            res.Data[i].evaluator = "";
            res.Data[i].evaluatorName = "";
            res.Data[i].evaluateServiceContent = "";
            res.Data[i].evaluateServiceDesc = "";
            res.Data[i].evaluateProductContent = "";
            res.Data[i].evaluateProductDesc = "";
          } else if (res.Data[i].currentState === 8) {
            res.Data[i].title = "进行中";
            res.Data[i].icon = "copyright";
            res.Data[i].desc = "工程师：" + res.Data[i].name + "(" + res.Data[i].username + res.Data[i].secondDepartment + ")正在维修.....";
            res.Data[i].traceSpeed = "";
            res.Data[i].traceDesc = "";
            res.Data[i].serviceAttitude = "";
            res.Data[i].serviceDesc = "";
            res.Data[i].evaluator = "";
            res.Data[i].evaluatorName = "";
            res.Data[i].evaluateServiceContent = "";
            res.Data[i].evaluateServiceDesc = "";
            res.Data[i].evaluateProductContent = "";
            res.Data[i].evaluateProductDesc = "";
          } else if (res.Data[i].currentState === 9) {
            res.Data[i].title = "订单暂停";
            res.Data[i].icon = "shake";
            res.Data[i].desc = "暂停原因：" + res.Data[i].reason;
            res.Data[i].traceSpeed = "";
            res.Data[i].traceDesc = "";
            res.Data[i].serviceAttitude = "";
            res.Data[i].serviceDesc = "";
          }else if (res.Data[i].currentState === 11) {
            res.Data[i].title = "已转单";
            res.Data[i].icon = "user";
            res.Data[i].desc = "已转单工程师："+ res.Data[i].name + "(" + res.Data[i].username + res.Data[i].secondDepartment + ")";
            res.Data[i].traceSpeed = "";
            res.Data[i].traceDesc = "";
            res.Data[i].serviceAttitude = "";
            res.Data[i].serviceDesc = "";
          } else if (res.Data[i].currentState === 10) {
            res.Data[i].title = "内部已关闭";
            res.Data[i].icon = "schedule";
            res.Data[i].desc = "内部已关闭";
            res.Data[i].traceSpeed = "";
            res.Data[i].traceDesc = "";
            res.Data[i].serviceAttitude = "";
            res.Data[i].serviceDesc = "";
          }else if (res.Data[i].currentState === 100) {
            res.Data[i].title = "废单";
            res.Data[i].icon = "stop";
            res.Data[i].desc = "工程师：" + res.Data[i].name + "(" + res.Data[i].username + res.Data[i].secondDepartment + ")执行废单操作" + " (备注:" + res.Data[i].wasterRemark + ")";
          }
        }
        this.processData = res.Data;
        console.log(this.processData);
      },
      // 点击继续;
      handleContinue () {
        this.$Modal.confirm({
          title: '确认继续吗?',
          okText: '确定',
          cancelText: '取消',
          onOk: async () => {
            // 工单继续接口;
            const res = await api.reqBillPause({
              afterSaleNumber: this.afterSaleNumber,
              state: 8,
              username: this.userName,
            });
            if (res.MsgCode === 0) {
              this.$Modal.success({
                title: '',
                content: '订单正在进行中!',
                okText: '确定',
                onOk: () => {
                  window.location.reload();
                }
              });
            } else {
              this.$message.error('操作失败...');
            }
          },
          onCancel() {},
          class: 'test',
        });
      },
      // 点击暂停;
      handlePause () {
        this.visible = true;
      },
      handleCancel () {
        this.visible = false;
      },
      handleCreate () {
        const form = this.$refs.collectionForm.form;
        form.validateFields( async (err, values) => {
          if (err) { return; }
          form.resetFields();
          this.visible = false;
          // 工单暂停接口;
          const res = await api.reqBillPause({
            afterSaleNumber: this.afterSaleNumber,
            state: 9,
            username: this.userName,
            reason: values.reason,
          });
          if (res.MsgCode === 0) {
            this.$Modal.success({
              title: '',
              content: '订单已暂停!',
              okText: '确定',
              onOk: () => {
                window.location.reload();
              }
            });
          } else {
            this.$message.error('暂停失败...');
          }
        })
      },

      handleMendInformation () {
        this.mendVisible = true;
      },
      handleMendCancel () {
        this.mendVisible = false;
      },
      // 添加维修信息;
      handleMendCreate () {
        const form = this.mendForm;
        form.validateFields( async (err, values) => {
          if (err) { return; }
          form.resetFields();
          this.mendVisible = false;
          // 添加维修信息接口;
          let repairData = {};
          repairData.time = getCurrentDate(2);
          repairData.record = values.record;
          repairData.pictureId = this.picturesId;
          repairData.afterSaleNumber = this.afterSaleNumber;
          repairData.username = this.userName;
          const jsonRepairData = JSON.stringify(repairData);
          console.log(jsonRepairData);
          api.reqHandleMendInformation(jsonRepairData).then((res) => {
            console.log(res);
            if (res.MsgCode === 0) {
              this.$Modal.success({
                title: '',
                content: '添加维修信息成功!',
                okText: '确定',
                onOk: () => {
                  window.location.reload();
                }
              });
            } else {
              this.$message.error('添加维修信息失败...');
            }
          })
        })
      },
      // 子组件传递过来的图片;
      changeFileList (fileList) {
        let picturesId = '';
        let pictureIdArr = [];
        if (fileList.length === 0) {
          picturesId = '';
        } else {
          for (let i = 0; i < fileList.length; i++) {
            pictureIdArr.push(fileList[i].id);
            picturesId = pictureIdArr.join(',');
          }
        }
        this.picturesId = picturesId;
      },
      // 判断按钮的显示与否;
      showBillContinue (suit, val) {
        if (suit === "true" && val === 8) {
          // 代表进行中，要显示暂停;
          this.showPause = true;
          this.allShow = true;
        } else if (suit === "true" && val === 9) {
          // 代表工单暂停，不显示暂停；
          this.showPause = false;
          this.allShow = true;
        } else {
          this.allShow = false;
        }
      }
    },
  }
</script>

<style scoped="scoped">
  @import "./style.css";
</style>
